import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Button, Modal, Form, Input, message, Table, DatePicker } from 'antd';
import { Link } from 'react-router-dom';
import api from '../services/api';
import { orderService } from '../services/orderService';
import { rankingService } from '../services/rankingService';
import locale from 'antd/es/date-picker/locale/zh_CN';
import dayjs from 'dayjs';

const UserDashboard = () => {
  const [user, setUser] = useState(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isPasswordModalVisible, setIsPasswordModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [ranking, setRanking] = useState(null);

  useEffect(() => {
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      const userData = JSON.parse(storedUser);
      setUser(userData);
      fetchOrders(userData.username);
      fetchRanking(userData.username);
    }
  }, []);

  const fetchOrders = async (username) => {
    setLoading(true);
    try {
      const today = dayjs();
      const startDate = today.startOf('month').format('YYYY-MM-DD');
      const endDate = today.endOf('month').format('YYYY-MM-DD');
      
      const data = await orderService.getOrdersByRange(startDate, endDate);
      const userOrders = data.filter(order => 
        order.companion === username || 
        order.customer === username ||
        order.dispatch === username ||
        order.receptionist === username
      );
      setOrders(userOrders);
    } catch (error) {
      message.error('获取订单数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchRanking = async (username) => {
    try {
      const today = dayjs();
      const year = today.year();
      const month = today.month() + 1;
      
      const [companionRanking, dispatchRanking, receptionistRanking] = await Promise.all([
        rankingService.getCompanionRanking(year, month),
        rankingService.getDispatchRanking(year, month),
        rankingService.getReceptionistRanking(year, month)
      ]);

      const allRankings = [...companionRanking, ...dispatchRanking, ...receptionistRanking];
      const userRanking = allRankings.find(rank => rank.name === username);
      setRanking(userRanking);
    } catch (error) {
      message.error('获取排名数据失败');
    }
  };

  const handleEdit = () => {
    setIsModalVisible(true);
    form.setFieldsValue(user);
  };

  const handlePasswordEdit = () => {
    setIsPasswordModalVisible(true);
  };

  const handleDelete = () => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除您的账户吗？此操作不可恢复。',
      onOk: () => {
        api.delete(`/users/${user.username}`)
          .then(() => {
            localStorage.removeItem('user');
            window.location.href = '/login';
          })
          .catch(error => {
            console.error('删除账户失败:', error);
            message.error('删除账户失败');
          });
      },
    });
  };

  const handleSubmit = (values) => {
    console.log('提交的用户信息:', values);
    api.put(`/users/${user.username}`, {
      email: values.email,
      phone: values.phone
    })
    .then(response => {
      console.log('更新后的用户信息:', response.data);
      setUser(response.data);
      localStorage.setItem('user', JSON.stringify(response.data));
      setIsModalVisible(false);
      message.success('个人信息更新成功');
    })
    .catch(error => {
      console.error('更新个人信息失败:', error);
      message.error(error.response?.data?.message || '更新个人信息失败');
    });
  };

  const handlePasswordSubmit = (values) => {
    api.put(`/api/users/${user.username}/password`, null, {
      params: {
        password: values.password
      }
    })
      .then(() => {
        setIsPasswordModalVisible(false);
        message.success('密码修改成功');
      })
      .catch(error => {
        console.error('修改密码失败:', error);
        message.error(error.response?.data?.message || '修改密码失败');
      });
  };

  const orderColumns = [
    { title: '订单ID', dataIndex: 'id', key: 'id' },
    { title: '派单员', dataIndex: 'dispatch', key: 'dispatch' },
    { title: '接待员', dataIndex: 'receptionist', key: 'receptionist' },
    { title: '陪玩', dataIndex: 'companion', key: 'companion' },
    { title: '客户', dataIndex: 'customer', key: 'customer' },
    { title: '服务类型', dataIndex: 'serviceType', key: 'serviceType' },
    { title: '时长(分钟)', dataIndex: 'duration', key: 'duration' },
    { 
      title: '总金额', 
      dataIndex: 'totalPrice', 
      key: 'totalPrice',
      render: (value) => `¥${value?.toFixed(2) || '0.00'}`
    },
    { 
      title: '最终金额', 
      dataIndex: 'finalAmount', 
      key: 'finalAmount',
      render: (value) => `¥${value?.toFixed(2) || '0.00'}`
    },
    { 
      title: '创建时间', 
      dataIndex: 'createTime', 
      key: 'createTime',
      render: (value) => dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    }
  ];

  return (
    <div style={{ padding: 24 }}>
      <h2 style={{ marginBottom: 24 }}>个人资料</h2>
      
      <Card title="个人信息" style={{ marginBottom: 24 }}>
        <Row gutter={16}>
          <Col span={12}>
            <Statistic title="用户名" value={user?.username} />
          </Col>
          <Col span={12}>
            <Statistic title="权限" value={user?.permission === 'user' ? '用户' : '管理员'} />
          </Col>
        </Row>
        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col span={8}>
            <Button type="primary" onClick={handleEdit}>修改信息</Button>
          </Col>
          <Col span={8}>
            <Button type="primary" onClick={handlePasswordEdit}>修改密码</Button>
          </Col>
          <Col span={8}>
            <Button type="primary" danger onClick={handleDelete} className="delete-button">删除账户</Button>
          </Col>
        </Row>
      </Card>

      <Card title="本月排名" style={{ marginBottom: 24 }}>
        {ranking ? (
          <Row gutter={16}>
            <Col span={6}>
              <Statistic title="排名" value={ranking.rank} suffix="名" />
            </Col>
            <Col span={6}>
              <Statistic title="订单数" value={ranking.orderCount} suffix="单" />
            </Col>
            <Col span={6}>
              <Statistic title="总流水" value={ranking.amount} precision={2} prefix="¥" />
            </Col>
            <Col span={6}>
              <Statistic title="实际收入" value={ranking.actualIncome} precision={2} prefix="¥" />
            </Col>
          </Row>
        ) : (
          <div>暂无排名数据</div>
        )}
      </Card>

      <Card title="本月订单">
        <Table
          columns={orderColumns}
          dataSource={orders}
          loading={loading}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
        />
      </Card>

      <Modal
        title="修改个人信息"
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form form={form} onFinish={handleSubmit}>
          <Form.Item 
            name="username" 
            label="用户名"
          >
            <Input disabled />
          </Form.Item>
          <Form.Item 
            name="email" 
            label="邮箱" 
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '邮箱格式不正确' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item 
            name="phone" 
            label="手机号" 
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">保存</Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="修改密码"
        visible={isPasswordModalVisible}
        onCancel={() => setIsPasswordModalVisible(false)}
        footer={null}
      >
        <Form form={passwordForm} onFinish={handlePasswordSubmit}>
          <Form.Item name="password" label="新密码" rules={[{ required: true, message: '请输入新密码' }]}>
            <Input.Password />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">保存</Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserDashboard;